/** *******************************************************************
 * Amfphp Redux
 * @author  Jonnie Spratley
 * @see jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.amfphpredux.commands
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.jonniespratley.amfphpredux.business.AmfphpReduxServiceDelegate;
	import com.jonniespratley.amfphpredux.events.GetTablesEvent;
	import com.jonniespratley.amfphpredux.model.ModelLocator;
	import com.jonniespratley.amfphpredux.vo.*;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	/**
	 * For every feature or use case in your application, a corresponding custom command
	 * and event must be created. Each command contains an execute() method that is run
	 * by the framework when the user action has been executed.
	 * These classes are occasionally referred to as worker classes because they carry
	 * out the work for an application.
	 *
	 */
	public class GetTablesCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			var evt:GetTablesEvent = event as GetTablesEvent;
			var delegate:AmfphpReduxServiceDelegate = new AmfphpReduxServiceDelegate( this );
				delegate.getTables( evt.aUser.host, evt.aUser.port, evt.aUser.username, evt.aUser.password, evt.aDatabase );

		}

		public function result( data:Object ) : void
		{
			var result:ResultEvent = data as ResultEvent;
			//model.tableCollection = new ArrayCollection( ArrayUtil.toArray( data.result ) );
			model.tableCollection = handleResults( result );
			
		}

		public function fault( fault:Object ):void
		{
			var faultEvt:FaultEvent = fault as FaultEvent;
			Alert.show(faultEvt.fault.toString(), "Error");
			trace(faultEvt.fault.faultString);
		}
	
		/* Populate comboboxes */
		private function handleResults( event:ResultEvent ):ArrayCollection
		{
			var databases:Object = new Object();
			var key:String;
			var databaseArray:Array = new Array();
			var array:Array = new Array();
			
			//Get setting structure.
			databases = event.result as Object;
			
			for( key in databases)
			{
				array.push( databases[ key ] );
			}
			//Populate data grid
			var collection:ArrayCollection = new ArrayCollection( array );
			
			return collection;
		}
	}
}
